<template>
    <section>
        <full-screen-dialog
            title="选择对账数据"
            v-model="visible"
            :width="1400"
            destroy-on-close
            @closed="$emit('closed')"
        >
            <el-foot>
                <vab-query-form-top-panel>
                    <el-form inline label-width="49px" :model="queryForm" style="margin-top: 5px">
                        <el-form-item label="采购单日期" label-width="100px">
							<el-date-picker style="width: 300px" v-model="queryList.applyDateTime"
								type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
								range-separator="-" unlink-panels="true" start-placeholder="开始时间"
								end-placeholder="结束时间"  :default-time="defaultTime"/>
                        </el-form-item>
                        <!-- <el-form-item label="采购入库单" label-width="100px">
							<el-input placeholder="---请输入采购入库单编号---" v-model="queryList.StorageOrderCode"
								style="width: 300px" />
                        </el-form-item>-->
                        <el-form-item label="门店" label-width="100px">
                            <el-input
                                placeholder="---请输入门店名称---"
                                v-model="queryList.StoreName"
                                style="width: 300px"
                            />
                        </el-form-item>

                        <el-form-item label="业务员" label-width="100px">
                            <el-input
                                placeholder="---请输入业务员名称---"
                                v-model="queryList.Salesman"
                                style="width: 300px"
                            />
                        </el-form-item>
                        <el-form-item label="制单人" label-width="100px">
                            <el-input
                                placeholder="---请输入制单人---"
                                v-model="queryList.DocumentsUser"
                                style="width: 300px"
                            />
                        </el-form-item>
                        <!-- <el-form-item label="对账状态" label-width="100px">
                        <el-select
                            placeholder="---请选择状态---"
                            v-model="queryList.Status"
                            style="width: 300px"
                        >
                            <el-option label="---请选择状态---" value />
                            <el-option
                                v-for="item in optionsState"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        </el-form-item>-->
                        <el-form-item label="关联订单" label-width="100px">
                            <el-input
                                placeholder="---请输入关联订单---"
                                v-model="queryList.PurchaseOrderCode"
                                style="width: 300px"
                            />
                        </el-form-item>
                        <el-form-item label="物料简码" label-width="100px">
                            <el-input
                                placeholder="---请输入物料简码---"
                                v-model="queryList.MaterialSimpCode"
                                style="width: 300px"
                            />
                        </el-form-item>
                        <el-form-item label="物料编号" label-width="100px">
                            <el-input
                                placeholder="---请输入物料编号---"
                                v-model="queryList.MaterialCode"
                                style="width: 300px"
                            />
                        </el-form-item>
                        <el-form-item label="物料分类" label-width="100px">
                            <el-tree-select
                                placeholder="---请选择物料分类---"
                                v-model="queryList.MaterialTypeIds"
                                :props="{ label: 'label', value:'value',children: 'children' }"
                                :data="materialTypeTree"
                                multiple
                                :render-after-expand="false"
                                show-checkbox
                                style="width: 300px"
                            />
                        </el-form-item>
                        <el-form-item label="物料名称" label-width="100px">
                            <el-input
                                placeholder="---请输入物料名称---"
                                v-model="queryList.MaterialName"
                                style="width: 300px"
                            />
                        </el-form-item>
                        <el-form-item label="规格型号" label-width="100px">
                            <el-input
                                placeholder="---请输入规格型号---"
                                v-model="queryList.MaterialSpecs"
                                style="width: 300px"
                            />
                        </el-form-item>
                        <el-form-item label label-width="100px">
                            <el-button
                                :icon="Search"
                                 
                                type="primary"
                                @click="onSearch"
                            >查询</el-button>
                            <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                        </el-form-item>
                    </el-form>
                </vab-query-form-top-panel>
            </el-foot>

            <el-main class="nopadding">
                <scTable
                    ref="mytable"
                    border
                    :queryType="'storage-order/list'"
                    :data="listData"
                    :queryList="queryList"
                    :column="columnList"
                    :totalCount="total"
                    :pageSize="pageSize"
                    :orderList="OrderList"
                    :sort-orders="['ascending', 'descending']"
                    @selection-change="selectionChange"
                    row-key="ReceivingOrderId"
                    key="ReceivingOrderId"
                    :row-class-name="setRowClass"
                    show-summary
                    :summary-method="getSummaries"
                >
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column label="序号" type="index" width="55"></el-table-column>
                    <el-table-column
                        label="对账状态"
                        prop="supplierStatusDesc"
                        width="100"
                        v-if="orgType==1"
                    ></el-table-column>
                    <el-table-column
                        label="对账状态"
                        prop="wineStatusDesc"
                        width="100"
                        v-if="orgType==3"
                    ></el-table-column>
                    <el-table-column label="业务日期" prop="applyDate" width="120">
                        <template #default="scope">{{scope.row.applyDate?.slice(0,10)}}</template>
                    </el-table-column>
                    <el-table-column
                        label="单据编号"
                        prop="storageOrderCode"
                        width="200"
                        v-if="orgType==1"
                    ></el-table-column>
                    <el-table-column label="类型" prop="storageOrderTypeDesc" width="100"></el-table-column>
                    <el-table-column label="门店" prop="storeName" width="120"></el-table-column>
                    
                    <el-table-column label="物料名称" prop="materialName" width="130"></el-table-column>
                    <el-table-column label="规格型号" prop="materialSpecs" width="100"></el-table-column>
                    <el-table-column label="数量" prop="purchaseQty" width="80"></el-table-column>
                    <el-table-column label="单位" prop="unitName" width="65"></el-table-column>
                    <el-table-column label="单价" prop="purchasePrice" width="90"></el-table-column>
                    <el-table-column label="金额" prop="purchaseTotalAmount" width="100"></el-table-column>
                    <el-table-column label="物料编码" prop="materialCode" width="100"></el-table-column>
                    <el-table-column label="关联订单" prop="purchaseOrderCode" width="200"></el-table-column>
                    <el-table-column label="业务员" prop="salesman" width="100" v-if="orgType==1"></el-table-column>
                    <el-table-column label="制单人" prop="documentsUser" width="100" v-if="orgType==1"></el-table-column>
                </scTable>
            </el-main>

            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="visible = false">关 闭</el-button>
                    <el-button type="primary" @click="submit()">确认添加</el-button>
                </div>
            </template>
        </full-screen-dialog>
    </section>
</template>

<script>
import tool from "@/utils/tool";
export default {
    emits: ["checkTable"],
    data() {
        return {
            visible: false,
            orgType: "",
            columnList: [],
            queryList: {
                SupplierId: tool.data.get("USER_INFO").OrgId,
                PurchaseUnityId: "",
            },
            materialTypeTree: [],
            selectionRows: [],
            listData: [],
            total: 0,
            pageSize: 10,
            showCondition: false,
            columnIndex0: "",
            columnIndex17: "",
            columnIndex15: "",
            dialogPrint: false,
            dialogCheck: false,
            dialogReconciliatio: false,
            PurchaseUnityId: "",
            supplierId: 0,
            supplierOrgType:3,
            storageOrderAccountTimes: [],
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
        };
    },
    methods: {
        submit() {
            console.log("submit...", this.selectionRows);
            // 将选中的数据的 storageOrderCode 转换为一个集合（用于快速查找）
            //const smallSet = new Set(this.selectionRows.map(item => item.storageOrderCode));

            // 使用 filter 方法遍历表格数据，筛选符合条件的对象
            //const resultArray = this.listData.filter(item => smallSet.has(item.storageOrderCode));
            //console.log("resultArray",resultArray)
            this.$emit("checkTable", this.selectionRows);
            this.visible = false;
        },
        initData(
            PurchaseUnityId = "",
            storageOrderAccountTimes,
            supplierId,
            notStorageOrderIds,
            supplierOrgType=3
        ) {

            console.log("时间",storageOrderAccountTimes)
            console.log("供应商",supplierId)

            this.visible = true;
            this.orgType = tool.data.get("USER_INFO").AccountType;
            if (this.orgType == 1) {
                this.queryList.WineStatus = 0;
            } else {
                this.queryList.SupplierStatus = 0;
            }
            this.PurchaseUnityId = PurchaseUnityId;
            this.supplierOrgType = supplierOrgType;
            this.supplierId = supplierId;
            this.storageOrderAccountTimes = storageOrderAccountTimes;
            this.notStorageOrderIds = notStorageOrderIds;
            this.queryList.SupplierId = supplierId;
            this.queryList.supplierOrgType = supplierOrgType;
            this.queryList.PurchaseUnityId = PurchaseUnityId;
            this.queryList.applyDateTime = this.storageOrderAccountTimes;
            this.queryList.isStorageOrderAccount = 0;
            //this.queryList.StorageOrderTimes=storageOrderAccountTimes;
            this.queryList.notStorageOrderIds = this.notStorageOrderIds;
            console.log(this.queryList);
            this.$nextTick(() => {
                this.initOptions();
                this.searchData();
            });
        },
        async searchData() {
            console.log(this.queryList);
            try {
                const { response, status } =
                    await this.$API.auth.PostProcessApi.post(
                        "storage-order/list",
                        this.queryList
                    );
                if (status == 200) {
                    console.log("response", response);
                    this.listData = response.data;
                    this.total = response.dataCount;
                    this.pageSize = response.pageSize;
                }
            } catch (error) {}
        },
        async opBindData() {
            this.listData = [];
            this.$refs.mytable.clearSort();
            // this.$refs.mytable.getData();
        },
        onSearch() {
            this.listData = [];
            this.$refs.mytable.clearSort();
            this.$refs.mytable.getData();
        },
        resetSearch() {
            this.queryList = {
                SupplierId: this.supplierId,
                PurchaseUnityId: this.PurchaseUnityId,
                applyDateTime: this.storageOrderAccountTimes,
                notStorageOrderIds: this.notStorageOrderIds,
                isStorageOrderAccount :0
            };
            if (this.orgType == 1) {
                this.queryList.WineStatus = 0;
            } else {
                this.queryList.SupplierStatus = 0;
            }
        },
        setRowClass({ row }) {
            if (this.selectionRows.includes(row)) {
                return "selected-row-color";
            }
            return "";
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        //核对
        opCheck(row) {
            this.dialogCheck = true;
            this.$nextTick(() => {
                this.$refs.checkDialog.setData(row);
                this.$refs.checkDialog.open("Check");
            });
        },
        opPrintview(row) {
            this.dialogPrint = true;
            this.$nextTick(() => {
                var arr = [];
                arr.push(row);
                this.$refs.printDialog.setData(arr);
                this.$refs.printDialog.open("Show");
            });
        },
        //查看
        opShow(row) {
            this.dialogCheck = true;
            this.$nextTick(() => {
                this.$refs.checkDialog.setData(row);
                this.$refs.checkDialog.open("Show");
            });
        },
        allprintview() {
            if (this.selectionRows.length > 0) {
                this.dialogPrint = true;
                let uniqueArr = this.selectionRows.filter(
                    (item, index, self) =>
                        index ===
                        self.findIndex(
                            (t) => t.receivingOrderId === item.receivingOrderId
                        )
                );
                this.$nextTick(() => {
                    this.$refs.printDialog.setData(uniqueArr);
                    this.$refs.printDialog.open("Show");
                });
            } else {
                this.$message.error("请选择要打印的数据");
            }
        },
        async allaccount() {
            if (this.selectionRows.length > 0) {
                let uniqueArr = this.selectionRows.filter(
                    (item, index, self) =>
                        index ===
                        self.findIndex(
                            (t) => t.receivingOrderId === item.receivingOrderId
                        )
                );
                var ids = uniqueArr.map((item) => {
                    return item.receivingOrderId;
                });
                const returnValue = await this.$API.auth.PostProcessApi.post(
                    "receiving-order/account",
                    ids
                );
                if (returnValue.status == 200) {
                    this.$message.success(returnValue.msg);
                    await this.opBindData();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } else {
                this.$message.error("请选择要对账的数据");
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    {
                        status: 1,
                    }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "storage-order/list",
                    this.queryList
                );
                if (returnValue.status == 200) {
                    this.listData = returnValue.response.data;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        // objectSpanMethod({
        // 	row,
        // 	column,
        // 	rowIndex,
        // 	columnIndex
        // }) {
        // 	if (columnIndex === 0) {
        // 		if (this.columnIndex1 != row.storageOrderCode) {
        // 			this.columnIndex1 = row.storageOrderCode;
        // 			return {
        // 				rowspan: row.itemCount,
        // 				colspan: 1
        // 			};
        // 		} else {
        // 			return {
        // 				rowspan: 0,
        // 				colspan: 0
        // 			};
        // 		}
        // 	}

        // },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            console.log(111);

            if (columnIndex === 0) {
                // Check if it's the column for storageOrderCode
                const currentRow = this.listData[rowIndex];
                const prevRow = this.listData[rowIndex - 1];

                if (
                    prevRow &&
                    prevRow.storageOrderCode === currentRow.storageOrderCode
                ) {
                    console.log(prevRow.storageOrderCode);

                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                }

                let rowspan = 1;
                for (let i = rowIndex + 1; i < this.listData.length; i++) {
                    if (
                        this.listData[i].storageOrderCode ===
                        currentRow.storageOrderCode
                    ) {
                        rowspan++;
                    } else {
                        break;
                    }
                }

                return {
                    rowspan,
                    colspan: 1,
                };
            }
        },
        //合计 
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) =>
                    Number(item[column.property])
                );

                if (column.property == "purchaseQty") {
                    var qtySum = 0;
                    this.selectionRows.map((selectItem) => {
                        qtySum += selectItem.purchaseQty;
                    });
                    sums[index] = qtySum;
                }
                // if (column.property == "price") {
                //     var PriceSum = 0;
                //     this.selectionRows.map((selectItem) => {
                //         PriceSum += selectItem.price;
                //     });
                //     sums[index] = PriceSum;
                // }

                if (column.property == "purchaseTotalAmount") {
                    let totalAmountSum = 0;
                    this.selectionRows.map((selectItem) => {
                        totalAmountSum += selectItem.purchaseTotalAmount;
                    });
                    sums[index] = totalAmountSum;
                }
            });
            return sums;
        },
    },
};
</script>

<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}

::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>
